<?php 
	include("includes/connect_db.php");

	$id = $_POST["id"];
	switch ($_GET['act']) {
		case 1:
			$html = "";
			if (count($id)>0) {
				foreach ($id as $value) {
					$sql = "SELECT * FROM tb_kontak_rincian	WHERE id_kontak = '$value' AND is_primary = 1";
					$query = mysql_query($sql);
					$baris = mysql_fetch_array($query);
					$tampil =  $baris['nama_rincian']." (".$baris['no_hp'].")";
					$panjang = strlen($tampil);
					if ($panjang > 45) {
						$kontak = substr($tampil, 0, 45);
						$kontak .= " ...";
					} else {
						$kontak = $tampil;
					}

					$html .= "<div class='kontakTampil' style='width: 90%' data-id='".$value."'>";
					$html .= "<span class='span11'>";
					$html .= $kontak;
					$html .= "</span>";
					$html .= "<span class='span1'>";
					$html .= "<i class='icon-remove icon-white hapus'></i>";
					$html .= "</span>";
					$html .= "</div>";
				}
			}else{
				$html .= "<div>No Contact Selected..</div>";
			}
			echo $html;
			break;
		
		case 2:
			$nama = $_POST['nama'];
			$deskripsi = $_POST['deskripsi'];
			$jumlah = count($id);

			$query = "SHOW TABLE STATUS LIKE 'tb_group_kontak'";
			$hasil = mysql_query($query);
			$data  = mysql_fetch_array($hasil);
			$newID = $data['Auto_increment'];

			$sql_cek = "SELECT * FROM tb_group_kontak WHERE nama_group='$nama'";
			$query_cek = mysql_query($sql_cek);
			$cek = mysql_num_rows($query_cek);

			if ($cek == 0) {
				$sql_insert = "INSERT INTO tb_group_kontak(nama_group, deskripsi) VALUES ('$nama', '$deskripsi')";

				if ($query_insert = mysql_query($sql_insert)) {
					for ($i=0; $i <= $jumlah; $i++) { 
						$sql_detail = "INSERT INTO tb_detail_kontak(id_group, id_kontak) VALUES ('$newID', '$id[$i]')";
						$query_detail = mysql_query($sql_detail);
					}
				}
			} else{
				echo "valid";
			}
			break;

		case 3:
			$sql_hapus = "DELETE FROM tb_group_kontak WHERE id_group = '$id'";
			$query_hapus = mysql_query($sql_hapus);

			$sql_hapus_detail = "DELETE FROM tb_detail_kontak WHERE id_group = '$id'";
			$query_hapus_detail = mysql_query($sql_hapus_detail);
			break;

		case 4:
			$nama = $_POST['nama'];
			$deskripsi = $_POST['deskripsi'];
			$idGroup = $_POST['idGroup'];
			$jumlah = count($id);

			$sql_update = "UPDATE tb_group_kontak SET nama_group='$nama', deskripsi='$deskripsi' WHERE id_group='$idGroup'";

			if ($query_update = mysql_query($sql_update)) {
				$sql_delete = "DELETE FROM tb_detail_kontak WHERE id_group='$idGroup'";
				$query_delete = mysql_query($sql_delete);
				for ($i=0; $i <= $jumlah; $i++) { 
					$sql_detail = "INSERT INTO tb_detail_kontak(id_group, id_kontak) VALUES ('$idGroup', '$id[$i]')";
					$query_detail = mysql_query($sql_detail);
				}
			}
			break;
	}

?>